<template>
	<view>
		<tui-sticky :scrollTop="scrollTop" stickyHeight="51px" container>
			<view class="padding bg-white" slot="header" ref="sticky">
				<u-search @search="list" placeholder="角色名称查询" v-model="pageRequest.condition.roleName" action-text="确定" @custom="save"></u-search>
			</view>
			<template slot="content">
				<view class="margin-top flex flex-direction">
					<u-checkbox-group class="solid-bottom bg-white flex flex-direction flex-sub" @change="selectChange">
						<u-checkbox 
							class="padding flex-sub"
							v-for="(item, index) in pageData.content" 
							:key="item.id" 
							v-model="item.checked" 
							:name="item.id">
							{{item.roleName}}({{item.roleCode}})
						</u-checkbox>
					</u-checkbox-group>
					<u-loadmore :status="pageData.page < pageData.pages ? 'loading' : 'nomore'" bg-color="" class="padding" />
				</view>
			</template>
		</tui-sticky>
	</view>
</template>

<script>
export default {
	onLoad: function(option) {
		if (option.info) {
			let info = JSON.parse(decodeURIComponent(option.info));
			this.info.orgId = info.id;
		}
		this.list();
	},
	onPullDownRefresh:function(){
		this.listSelect(true);
	},
	onReachBottom: function() {
		this.listSelect();
	},
	//页面滚动执行方式
	onPageScroll: function(e) {
		this.scrollTop = e.scrollTop;
	},
	data() {
		return {
			scrollTop: 0, // 滚动高度
			pageRequest: {
				page: 1,
				rows: 15,
				sort: 'id:asc',
				condition: {}
			},
			pageData: {
				page: 1,
				pages: 1,
				content: []
			},
			info: {
				orgId: '', // 权限ID
				roleIds: [], // 资源ID列表
			}
		};
	},
	methods: {
		list: function() {
			this.$request.get(`/admin/sys/org-role/getIds/${this.info.orgId}`, {}, res => {
				this.info.roleIds = res.data || [];
				this.listSelect(true);
			});
		},
		listSelect: function(first) {
			if (first) {
				this.pageRequest.page = 1;
			} else {
				if (this.pageData.page < this.pageData.pages) {
					this.pageRequest.page = this.pageRequest.page + 1;
				} else {
					return;
				}
			}
			this.$request.post(
				'/admin/sys/role/list',
				this.pageRequest,
				res => {
					let pageData = res.data || {};
					pageData.content.forEach(item => {
						for(let i in this.info.roleIds) {
							if (this.info.roleIds[i] == item.id) {
								item.checked = true;
							}
						}
					});
					if (this.pageRequest.page > 1) {
						pageData.content = (this.pageData.content || []).concat(pageData.content);
					}
					this.pageData = pageData;
				},
				false,
				false,
				true
			);
		},
		selectChange: function(e) {
			this.info.roleIds = e || [];
		},
		save: function() {
			this.$request.post(`/admin/sys/org-role/save`, this.info, res => {
				this.$utils.showModal('保存成功！', () => {
					uni.navigateBack({
						delta: 1
					});
				});
			}, false, true ,true);
		},
	}
};
</script>

<style lang="scss" scoped></style>
